<?php
require_once "../../../source/lib/class/file.php";

class xheditor extends file{
    private $inputname = 'filedata';//表单文件域name
    private $attachdir = "../../../data/upload/";//上传文件保存的主目录
    private $maxAttachSize=2097152;//最大上传大小，默认是2M
    //private $upExt='txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid';//上传扩展名
    private $upExt='jpg,jpeg,gif,png,swf';//上传扩展名
    
    /**
    * 构造函数
    * 
    */
    public function xheditor(){
        
    }
    
    
    public function xheditor_upload($dist_dir){
        $rtn = array('err'=>'','msg'=>'');
        $tempPath = 'upload/' . rand(1000, 9999) . '.tmp';//临时文件存放路径
        if(isset($_SERVER['HTTP_CONTENT_DISPOSITION'])&&preg_match('/attachment;\s+name="(.+?)";\s+filename="(.+?)"/i',$_SERVER['HTTP_CONTENT_DISPOSITION'],$info)){//HTML5上传
            if(!@file_put_contents($tempPath,file_get_contents("php://input"))){
                $rtn['err'] = '上传失败';
            }
            $localName=urldecode($info[2]);//得到文件本身的名称
        }else{
            $upfile=@$_FILES[$this->inputname];
            if(!isset($upfile)){
                $rtn['err']='文件域的name错误';                
            }elseif(!empty($upfile['error'])){
                switch($upfile['error'])
                {
                    case '1':
                        $rtn['err'] = '文件大小超过了php.ini定义的upload_max_filesize值';
                        break;
                    case '2':
                        $rtn['err'] = '文件大小超过了HTML定义的MAX_FILE_SIZE值';
                        break;
                    case '3':
                        $rtn['err'] = '文件上传不完全';
                        break;
                    case '4':
                        $rtn['err'] = '无文件上传';
                        break;
                    case '6':
                        $rtn['err'] = '缺少临时文件夹';
                        break;
                    case '7':
                        $rtn['err'] = '写文件失败';
                        break;
                    case '8':
                        $rtn['err'] = '上传被其它扩展中断';
                        break;
                    case '999':
                    default:
                        $rtn['err'] = '无有效错误代码';
                }
            }
            elseif(empty($upfile['tmp_name']) || $upfile['tmp_name'] == 'none'){
                $rtn['err'] = '无文件上传';
            }else{
                move_uploaded_file($upfile['tmp_name'],$tempPath);
                $localName=$upfile['name'];
            }
        }
        if($rtn['err']==''){
            $fileInfo=pathinfo($localName);
            $extension=$fileInfo['extension'];
            if(preg_match('/'.str_replace(',','|',$this->upExt).'/i',$extension))
            {//检查扩展名
                $bytes=filesize($tempPath);
                if($bytes > $this->maxAttachSize){
                    $rtn['err']='请不要上传大小超过'.$this->formatBytes($this->maxAttachSize).'的文件';
                }else{
                    $filename = $dist_dir . '/' . date('Y/m/');
                    $this->make_dir(realpath($this->attachdir) . '/' .$filename);
                    $filename .= substr(md5(microtime()), 8, 16).'.'.$fileInfo['extension'];
                    $targetpath = realpath($this->attachdir) . '/' . $filename;
                    $this->make_dir($filename);
                    rename($tempPath,$targetpath);
                    $rtn['msg'] = array();
                    $rtn['msg']['url'] = '/data/upload/' . $filename;
                    $rtn['msg']['localname'] = $localName;
                }
            }
            else{
                $rtn['err']='上传文件扩展名必需为：'.$this->upExt;
            }
            //删除临时文件
            @unlink($tempPath);
        }
        return $rtn;
    }
    private function formatBytes($bytes) {
        if($bytes >= 1073741824) {
            $bytes = round($bytes / 1073741824 * 100) / 100 . 'GB';
        } elseif($bytes >= 1048576) {
            $bytes = round($bytes / 1048576 * 100) / 100 . 'MB';
        } elseif($bytes >= 1024) {
            $bytes = round($bytes / 1024 * 100) / 100 . 'KB';
        } else {
            $bytes = $bytes . 'Bytes';
        }
        return $bytes;
    }
    
    public function make_dir($folder)
        {
            $reval = false;
            $exist = file_exists($folder);
            //如果文件夹存在
            if($exist){
                $reval = is_dir($folder);
                return  $reval;
            }
            //如果不存在则开始创建
            @umask(0);
            /* 将目录路径拆分成数组 */
            preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
            /* 如果第一个字符为/则当作物理路径处理 */
            $base = ($atmp[0][0] == '/') ? '/' : '';
            /* 遍历包含路径信息的数组 */
            foreach ($atmp[1] AS $val)
            {
                if($val == ''){
                    continue;
                }
                $base .= $val;
                if ($val == '..' || $val == '.')
                {
                    /* 如果目录为.或者..则直接补/继续下一个循环 */
                    $base .= '/';
                    continue;
                }
                $base .= '/';
                //如果目录存在则继续
                if(file_exists($base)){
                    continue;
                }
                /* 尝试创建目录，如果创建失败则继续循环 */
                if (@mkdir(rtrim($base, '/'), 0777))
                {
                    @chmod($base, 0777);
                    $reval = true;
                }
            }
            clearstatcache();
            return $reval;
        }
}
?>
